//
//  TopListDetailVC.m
//  Buiom_7.0
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 triffe. All rights reserved.
//

#import "TopListDetailVC.h"
#import "TopListDetailModel.h"
#import "FifthCell.h"
#import "SixCell.h"
#import "SeventhCell.h"

@interface TopListDetailVC ()<UITableViewDataSource,UITableViewDelegate,MONActivityIndicatorViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
// titlename
@property (nonatomic, strong) NSString *titleName;
@property (nonatomic, strong) NSString *summary;
@property (nonatomic, strong) NSNumber *page;

@property (nonatomic, strong) NSMutableArray *dataArray;


@property (nonatomic, strong) NSDictionary *dictioary;

@property (nonatomic, strong) NSNumber *count;

@property (nonatomic, assign) NSInteger numberToNSNumber;

@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@end

@implementation TopListDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;
    [self.view addSubview:self.tableView];
    [self setUpdataWithTopListURL];
    self.page = [NSNumber numberWithInt:1];
    self.numberToNSNumber = 1;
#pragma mark -- 上下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing) dateKey:@"YG"];
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"刷新中。。。";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"加载中。。。";
    
    
    
    // 添加动画加载等待
    self.indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.tableView.center;
    CGPoint point = _indicatorView.center;
    point.y = self.tableView.center.y - 200;
    _indicatorView.center = point;
    _indicatorView.delegate = self;
    [self.tableView addSubview:_indicatorView];
    [_indicatorView startAnimating];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"houtuiyibu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeft:)];
    self.navigationItem.leftBarButtonItem = left;
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionTopListRight:)];
    self.navigationItem.rightBarButtonItem = right;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"FifthCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"fifthCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SixCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"sixCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SeventhCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"seventhCell"];
    
    
    
}

#pragma mark -- 添加加载圆圈动画的方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    if (index == 0) {
        return [UIColor redColor];
    }if (index == 1) {
        return [UIColor magentaColor];
    }if (index == 2) {
        return [UIColor orangeColor];
    }if (index == 3) {
        return [UIColor purpleColor];
    }
    return [UIColor yellowColor];
}

- (void)actionTopListRight:(UIBarButtonItem *)bar
{
    NSString *shareString = [NSString stringWithFormat:@"%@\n%@",self.titleStr,self.summaryStr];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56374807e0f55a245800042a" shareText:shareString shareImage:[UIImage imageNamed:@"106.jpg"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToTwitter,UMShareToDouban,UMShareToRenren,nil] delegate:nil];
}


#pragma mark -- 实现上下拉加载刷新
// 下拉刷新
- (void)headerRefreshing
{
    
    [self.dataArray removeAllObjects];
    [self setUpdataWithTopListURL];
    [self.tableView headerEndRefreshing];
}

// 上拉加载
- (void)footerRereshing
{
    if ([self.page intValue] == 1) {
        [self.tableView footerEndRefreshing];
        return;
    } else if (self.numberToNSNumber < [self.page intValue]){
        self.numberToNSNumber++;
        NSString *urlStr = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=%ld&topListId=%@",(long)self.numberToNSNumber, self.topID];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            self.dictioary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *diction = self.dictioary[@"topList"];
            self.titleName = diction[@"name"];
            self.summary = diction[@"summary"];
            self.page = self.dictioary[@"pageCount"];
            if (self.dictioary[@"persons"]) {
                NSArray *array = self.dictioary[@"persons"];
                for (NSDictionary *dic in array) {
                    TopListDetailModel *model = [[TopListDetailModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
            } else if (self.dictioary[@"movies"]) {
                NSArray *array = self.dictioary[@"movies"];
                for (NSDictionary *dic in array) {
                    TopListDetailModel *model = [[TopListDetailModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
                
            }
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
        }];
        return;

    }
//    //2,结束刷新
    [self.tableView footerEndRefreshing];
}







- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count + 1;
}

// 实现方法
- (void)actionLeft:(UIBarButtonItem *)bar
{
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataArray.count > 0) {
        if (indexPath.row == 0) {
            SeventhCell *cell = [tableView dequeueReusableCellWithIdentifier:@"seventhCell" forIndexPath:indexPath];
            cell.titleLable.text = self.titleName;
            cell.summaryLable.text = self.summary;
            return cell;
        } else if (self.dictioary[@"movies"]) {
            TopListDetailModel *model = self.dataArray[indexPath.row - 1];
            FifthCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fifthCell" forIndexPath:indexPath];
            cell.userInteractionEnabled = NO;
            [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.posterUrl] placeholderImage:nil];
            cell.titleLable.text = model.name;
            cell.dictiorLable.text = model.director;
            cell.actorLable.text = model.actor;
            cell.dateLable.text = model.releaseDate;
            cell.summaryLable.text = model.remark;
            cell.numberLable.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
            return cell;
        } else if (self.dictioary[@"persons"]){
            TopListDetailModel *model = self.dataArray[indexPath.row - 1];
            SixCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sixCell" forIndexPath:indexPath];
            cell.userInteractionEnabled = NO;
            [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.posterUrl] placeholderImage:nil];
            cell.nameLable.text = model.nameCn;
            cell.sexLable.text = [NSString stringWithFormat:@"%@,%@",model.sex,model.birthDay];
            cell.summaryLable.text = model.summary;
            cell.numberLable.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
            return cell;

        }

    }
    NSString *identifier = @"SY";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }

    return cell;
}


#pragma mark -- 网络解析
- (void)setUpdataWithTopListURL
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.m.mtime.cn/TopList/TopListDetails.api?pageIndex=1&topListId=%@",self.topID];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        self.dictioary = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *diction = self.dictioary[@"topList"];
        self.titleName = diction[@"name"];
        self.summary = diction[@"summary"];
        self.page = self.dictioary[@"pageCount"];
        if (self.dictioary[@"persons"]) {
            NSArray *array = self.dictioary[@"persons"];
            for (NSDictionary *dic in array) {
                TopListDetailModel *model = [[TopListDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
        } else if (self.dictioary[@"movies"]) {
            NSArray *array = self.dictioary[@"movies"];
            for (NSDictionary *dic in array) {
                TopListDetailModel *model = [[TopListDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }

        }
        [self.tableView reloadData];
        [_indicatorView stopAnimating];
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath == 0) {
        return 50;
    } else if (self.dictioary[@"movies"] && indexPath.row != 0){
        return 210;
    } else if (self.dictioary[@"persons"] && indexPath.row != 0) {
        return 130;
    }
    return 100;
}


-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
